package com.oa.admin.controller;

import com.joneying.common.annotation.CommonController;
import com.joneying.common.web.response.Resp;
import com.oa.admin.dto.WorkReportListDTO;
import com.oa.admin.entity.WorkReport;
import com.oa.admin.service.IWorkReportService;
import com.oa.core.BaseController;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RequestMapping("/workReport")
@RestController
public class WorkReportController extends BaseController {

    @Autowired
    private IWorkReportService workReportService;

    @GetMapping("/list")
    @CommonController
    @Description("列表")
    @ApiOperation(value = "列表")
    public Resp list(WorkReportListDTO workReportListDTO) {
        workReportListDTO.setCopyUserIds(getLoginUserId());
        return new Resp().success(workReportService.findWorkReport(workReportListDTO));
    }

    @GetMapping("/{id}")
    @CommonController
    @Description("详情")
    @ApiOperation(value = "详情")
    public Resp findById(@PathVariable String id) {
        return new Resp().success(workReportService.selectById(id));
    }


    @PostMapping("")
    @CommonController
    @Description("添加")
    @ApiOperation(value = "添加")
    public Resp add(@RequestBody WorkReport workReport){
        workReport.setCreateTime(new Date());
        workReport.setUserId(getLoginUserId());

        List<String> copyUserIds = Arrays.asList(workReport.getCopyUserIds().split(","));

        boolean isMe = false;
        for (String copyUserId : copyUserIds) {
            if(copyUserId == getLoginUserId()){
                isMe = true;
                break;
            }
        }
        List<String> list = new ArrayList<>();
        list.addAll(copyUserIds);

        if(!isMe){
            list.add(getLoginUserId());
            workReport.setCopyUserIds(StringUtils.join(list.toArray(), ",").trim());
        }

        if(workReportService.insert(workReport)){
            return new Resp().success();
        }
        return new Resp().failure();
    }
}
